import type { DetectRequest, FilterStatus, ScanResult, DetectResult } from '../types/ssh'
import { validateCIDR, exportToCSV } from '../utils/ssh'
import { useStatsStore } from '@/stores/stats'

export class SSHDetectorController {
  private statsStore = useStatsStore()

  async checkBackendHealth(): Promise<boolean> {
    try {
      const response = await fetch('/api/v2/health', {
        method: 'GET',
        headers: {
          'Accept': 'application/json'
        }
      })
      return response.ok
    } catch (err) {
      throw new Error('后端健康检查失败')
    }
  }

  async detectSSH(formData: DetectRequest, 
                 updateProgress: (data: any) => void,
                 onComplete: (results: DetectResult[]) => void,
                 onError: (message: string) => void) {
    if (!validateCIDR(formData.network)) {
      throw new Error('请输入有效的CIDR格式网段，例如：192.168.1.0/24')
    }

    const isBackendHealthy = await this.checkBackendHealth()
    if (!isBackendHealthy) {
      throw new Error('无法连接到后端服务，请确保后端服务已启动')
    }

    this.statsStore.clearStats()
    
    let retryCount = 0
    const maxRetries = 3

    const tryConnect = async () => {
      try {
        const response = await fetch('/api/v2/detect', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
          },
          body: JSON.stringify({
            network: formData.network,
            port: formData.port,
            username: formData.username,
            password: formData.password
          })
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const reader = response.body?.getReader()
        if (!reader) {
          throw new Error('无法获取响应流')
        }

        const decoder = new TextDecoder()
        let buffer = ''
        let lastMessageTime = Date.now()
        let currentData = ''

        while (true) {
          const { done, value } = await reader.read()
          if (done) break

          lastMessageTime = Date.now()
          buffer += decoder.decode(value, { stream: true })
          
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''

          for (const line of lines) {
            if (line.startsWith('data:')) {
              currentData = line.slice(5).trim()
              continue
            }
            
            if (line.trim() === '' && currentData) {
              try {
                const data = JSON.parse(currentData)
                updateProgress(data)
                
                switch (data.type) {
                  case 'complete':
                    const detectResults: DetectResult[] = (data.results || []).map((result: ScanResult) => ({
                      ...result,
                      timestamp: new Date().toISOString(),
                      request: {...formData},
                      port_open: result.status !== 'port_closed',
                      is_ssh: result.status === 'connected' || result.status === 'sudo_supported',
                      info: result.message || ''
                    }))
                    onComplete(detectResults)
                    return
                    
                  case 'error':
                    onError(data.message)
                    return
                }
                
                currentData = ''
              } catch (err) {
                throw new Error('解析SSE消息失败')
              }
            }
          }

          if (Date.now() - lastMessageTime > 30000) {
            throw new Error('连接超时')
          }
        }

      } catch (err: unknown) {
        if (retryCount < maxRetries) {
          retryCount++
          await new Promise(resolve => setTimeout(resolve, 3000))
          return tryConnect()
        } else {
          if (err instanceof Error) {
            if (err.message.includes('Failed to fetch')) {
              throw new Error('无法连接到后端服务，请确保后端服务已启动')
            } else if (err.message.includes('timeout')) {
              throw new Error('连接超时，请检查网络状态')
            } else {
              throw err
            }
          } else {
            throw new Error('连接失败，请重试')
          }
        }
      }
    }

    await tryConnect()
  }

  handleExport(results: any[], getStatusText: (status: string) => string) {
    const exportResult = exportToCSV(results, getStatusText)
    if (!exportResult) {
      throw new Error('没有可导出的数据')
    }
    return exportResult
  }
}